<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>snabbdom demo</title>
</head>
<body>
<div id="app"></div>
<button id="btn">change</button>

<script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom.js"></script>
<script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-class.js"></script>
<script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-props.js"></script>
<script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-style.js"></script>
<script src="https://cdn.bootcss.com/snabbdom/0.7.1/snabbdom-eventlisteners.js"></script>
<script src="https://cdn.bootcss.com/snabbdom/0.7.1/h.js"></script>
<script>
    var snabbdom = window.snabbdom
    // 定义patch
    var patch = snabbdom.init({
        snabbdom_class,
        snabbdom_props,
        snabbdom_style,
        snabbdom_eventlisteners
    })
    // 定义h
    var h = snabbdom.h


    var data = [
        {
            name: '张三',
            age: '20',
            address: '北京'
        },
        {
            name: '李四',
            age: '21',
            address: '上海'
        },
        {
            name: '王五',
            age: '22',
            address: '广州'
        }
    ]

    // 表头数据
    data.unshift({
        name: '姓名',
        age: '年龄',
        address: '地址'
    })

    // 获取容器
    var container = document.getElementById('app')

    // 渲染函数
    var vnode

    function render(data) {
        var newVnode = h(
            'table',
            {},
            data.map(item => { // return h('tr', {}, [h(td1, ...), th(d2, ...)])
                var tds = []
                for (const i in item) {
                    if (item.hasOwnProperty(i)) {
                        tds.push(h('td', {}, item[i] + ''))
                    }
                }
                return h('tr', {}, tds)
            })
        )

        if (vnode) {
            patch(vnode, newVnode)
        } else {
            // 初次渲染
            patch(container, newVnode)
        }

        // 存储当前vnode结果
        vnode = newVnode
    }

    render(data)

    var btnChange = document.getElementById('btn')
    btnChange.addEventListener('click', () => {
        data[1].age = Date.now()
        data[2].name = 'sss'
        // 重新渲染
        render(data)
    })
</script>
</body>
</html>